package org.system.core.controller.system;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.system.core.annotation.Log;
import org.system.core.common.PageResult;
import org.system.core.common.Result;
import org.system.core.domain.entity.SysDept;
import org.system.core.domain.entity.SysRole;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.model.TreeSelect;
import org.system.core.enums.BusinessType;
import org.system.core.service.system.SysDeptService;
import org.system.core.service.system.SysRoleService;
import org.system.core.service.system.SysUserService;
import org.system.core.utils.PageUtils;
import org.system.core.utils.poi.ExcelUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author baoRoot
 */
@RestController
@RequestMapping("/system/user")
@Api(tags={"用户模块"})
public class SysUserController {

    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public PageResult<SysUser> list(SysUser user) {
        logger.info("请求用户列表：{}", user);
        PageUtils.startPage();
        List<SysUser> list = sysUserService.selectUserList(user);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return PageResult.ok(pageInfo);
    }

    @GetMapping("/{userId}")
    @ApiOperation("获取用户详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public Result<Map<String, Object>> getUserInfo(@PathVariable("userId") Long userId) {
        logger.info("获取用户详细信息：{}", userId);
        return Result.ok(sysUserService.selectUserInfo(userId));
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = sysUserService.selectUserList(user);
        ExcelUtils<SysUser> util = new ExcelUtils<>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @PostMapping
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasAnyPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    public Result<String> addUser(@Validated @RequestBody SysUser user) {
        logger.info("新增用户：{}", user);
        sysUserService.insertUser(user);
        return Result.ok();
    }

    @PutMapping
    @ApiOperation("更新用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public Result<String> editUser(@Validated @RequestBody SysUser user) {
        logger.info("更新用户：{}", user);
        sysUserService.updateUser(user);
        return Result.ok();
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{userIds}")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    public Result<String> deleteUser(@PathVariable Long[] userIds) {
        logger.info("删除用户： {}", userIds);
        sysUserService.deleteUser(userIds);
        return Result.ok();
    }

    @PutMapping("/reset")
    @ApiOperation("重置用户密码")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    public Result<String> resetUserPassword(@RequestBody SysUser user){
        logger.info("重置用户密码： {}", user);
        sysUserService.resetUserPassword(user);
        return Result.ok();
    }

    @PutMapping("/status")
    @ApiOperation("修改用户状态")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public Result<String> changeStatus(@RequestBody SysUser user){
        logger.info("修改用户状态： {}", user);
        sysUserService.changeStatus(user);
        return Result.ok();
    }

    @ApiOperation("根据用户id获取用户角色")
    @GetMapping("/authRole/{userId}")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public Result<Map<String, Object>> authRole(@PathVariable("userId") Long userId) {
        logger.info("根据用户id获取用户角色： {}", userId);
        Map<String, Object> result = new HashMap<>();
        SysUser user = sysUserService.selectUserById(userId);
        List<SysRole> roles = sysRoleService.selectRolesByUserId(userId);
        result.put("user", user);
//        result.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        // todo 由于需要将超级管理员进行分配，那么暂时不用进行过滤
        result.put("roles", roles);
        return Result.ok(result);
    }

    @PutMapping("/authRole")
    @ApiOperation("用户角色授权")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    public Result<String> insertAuthRole(Long userId, Long[] roleIds) {
        logger.info("用户角色授权，用户 {}，角色： {}", userId, roleIds);
        sysUserService.insertUserAuth(userId, roleIds);
        return Result.ok();
    }

    @ApiOperation("获取部门树列表")
    @GetMapping("/deptTree")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public Result<List<TreeSelect>> deptTree(SysDept dept) {
        logger.info("获取部门树列表： {}", dept);
        return Result.ok(sysDeptService.selectDeptTreeList(dept));
    }

}
